package com.baizhi.controller;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@RestController
@Slf4j
public class UserController {

    /**
     * 生成验证码图片
     */
    @GetMapping("/user/getImage")
    public String getImageCode(HttpServletRequest request, HttpSession session) throws IOException {
        //1.使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2.将验证码放入servletContext作用域
        request.getSession().setAttribute("code", code);
        //3.将图片转为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(120, 30, byteArrayOutputStream, code);
        return "data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
    }
    @Autowired
    UserService userService;

    @PostMapping("/user/login")
    @ResponseBody
    public HashMap<String,Object> login(@RequestBody User user){

        HashMap<String, Object> map = new HashMap<>();
        User user1 = userService.queryOne(user.getUsername());
        System.out.println(user1);
        if (user1!=null){
            if(user1.getPassword().equals(user1.getPassword())){
                map.put("msg","登录成功");
                map.put("state",true);
                map.put("user",user1);
            }else{
                map.put("msg","密码输入不正确");
                map.put("state",false);
            }
        }else {
                map.put("msg","证号不存在");
                map.put("state",false);
        }
        return  map;
    }
    @PostMapping("/user/register")
    @ResponseBody
    public HashMap<String,Object> register(@RequestBody User user,String code,HttpServletRequest request){

        HashMap<String, Object> map = new HashMap<>();
        String code1 = (String) request.getSession().getAttribute("code");
        System.out.println(code1);
        System.out.println(code);
        if (code1.equals(code)){
                map.put("msg","提示:注册成功");
                map.put("state",true);
        }else {
            map.put("msg","提示:用户名已存在");
            map.put("state",false);
        }
        return  map;
    }
}
